<template>
  <div class="examination">
    <nav class="navBar">
      <div>考试科目：{{ paper.title }}( 满分{{ paper.score }}分 )</div>
      <div class="timmer">
        考试剩余时间：{{ hour }} 时 {{ min }} 分 {{ second }}秒
      </div>
      <div class="btn">
        <el-button @click="submitPaper(0)" type="danger" size="medium "
          >交卷</el-button
        >
        <!-- <el-button @click="toFullOrExit" type="warning" size="medium ">{{
          !isFullscreen ? "全屏" : "退出全屏"
        }}</el-button> -->
      </div>
    </nav>
    <aside class="contentOfExamination">
      <content class="leftCollapse">
        <el-collapse v-model="activeNames" @change="handleChange">
          <div class="checkedContent">
            <el-collapse-item
              title="单选题"
              name="1"
              v-if="singleChoice.length > 0"
            >
              <div
                v-for="(item, index) in singleChoice"
                :key="index"
                @click="clickQuestionHandle(index, '单选题', singleChoice)"
              >
                <div
                  v-if="item.status !== '2'"
                  class="contentIndex"
                  :class="{
                    checkedIndex: paperSingleIndex == index,
                    endIndex: item.myAnswer && paperSingleIndex !== index,
                  }"
                >
                  {{ index + 1 }}
                </div>
                <div class="startindex" v-if="item.status == '2'">
                  {{ index + 1 }}
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item
              title="多选题"
              name="2"
              v-if="multipleChoice.length > 0"
            >
              <div
                v-for="(item, index) in multipleChoice"
                :key="index"
                @click="clickQuestionHandle(index, '多选题', multipleChoice)"
              >
                <div
                  v-if="item.status !== '2'"
                  class="contentIndex"
                  :class="{
                    checkedIndex: multipleChoiceIndex == index,
                    endIndex: item.myAnswer && multipleChoiceIndex !== index,
                  }"
                >
                  {{ index + 1 }}
                </div>
                <div class="startindex" v-if="item.status == '2'">
                  {{ index + 1 }}
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item
              title="判断题"
              name="3"
              v-if="judgeChoice.length > 0"
            >
              <div
                v-for="(item, index) in judgeChoice"
                :key="index"
                @click="clickQuestionHandle(index, '判断题', judgeChoice)"
              >
                <div
                  v-if="item.status !== '2'"
                  class="contentIndex"
                  :class="{
                    checkedIndex: judgeChoiceIndex == index,
                    endIndex: item.myAnswer && judgeChoiceIndex !== index,
                  }"
                >
                  {{ index + 1 }}
                </div>
                <div class="startindex" v-if="item.status == '2'">
                  {{ index + 1 }}
                </div>
              </div>
            </el-collapse-item>
          </div>
        </el-collapse>
      </content>
      <article class="rightCollapse">
        <nav>
          <div class="navContent" v-if="title == '单选题'">
            <span class="titleClass">{{ title }}</span>
            <span class="scoreBoard"
              >（共{{ singleChoice.length }}题,每题{{
                singleChoice[0]?.questionScore
              }}分 ）</span
            >
          </div>
          <div class="navContent" v-if="title == '多选题'">
            <span class="titleClass">{{ title }}</span>
            <span class="scoreBoard"
              >（共{{ multipleChoice.length }}题,每题{{
                multipleChoice[0]?.questionScore
              }}分 ）</span
            >
          </div>
          <div class="navContent" v-if="title == '判断题'">
            <span class="titleClass">{{ title }}</span>
            <span class="scoreBoard"
              >（共{{ judgeChoice.length }}题,每题{{
                judgeChoice[0]?.questionScore
              }}分 ）</span
            >
          </div>
        </nav>
        <aside
          class="testContent"
          v-if="title === '单选题' && singleChoice.length > 0"
        >
          <div class="questionTitle">
            {{ singleChoice[paperSingleIndex]?.questionNumber }}、{{
              singleChoice[paperSingleIndex]?.questionName
            }}
            <span class="answer"> {{ checkedNum }}</span>
          </div>

         <div class="questionTitle2" >
          <el-radio-group
            ref="radioGroup"
            v-model="radio"
            size="medium"
            @change="radioChange"
            @keydown="handleKeyDown"
          >
            <el-radio :label="2" data-key="a" v-if="!questionClass">
              A:
              <div>{{ singleChoice[paperSingleIndex]?.optionA }}</div>
            </el-radio>
            <el-radio :label="2" data-key="a" v-if="questionClass"
              >A:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + singleChoice[paperSingleIndex]?.optionA"
            /></el-radio>

            <el-radio :label="3" data-key="b" v-if="!questionClass"
              >B:
              <div>{{ singleChoice[paperSingleIndex]?.optionB }}</div></el-radio
            >
            <el-radio :label="3" data-key="b" v-if="questionClass"
              >B:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + singleChoice[paperSingleIndex]?.optionB"
            /></el-radio>
            <el-radio :label="4" data-key="c" v-if="!questionClass"
              ><div>
                C:
                <div>{{ singleChoice[paperSingleIndex]?.optionC }}</div>
              </div></el-radio
            >
            <el-radio :label="4" data-key="c" v-if="questionClass"
              >C:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + singleChoice[paperSingleIndex]?.optionC"
            /></el-radio>
            <el-radio
              :label="5"
              data-key="d"
              v-if="
                !questionClass &&
                singleChoice[paperSingleIndex]?.optionD.length > 0 &&
                singleChoice[paperSingleIndex]?.optionD !== ' '
              "
              >D:
              <div>{{ singleChoice[paperSingleIndex]?.optionD }}</div></el-radio
            >
            <el-radio
              :label="5"
              data-key="d"
              v-if="
                questionClass &&
                singleChoice[paperSingleIndex]?.optionD.length > 0 &&
                singleChoice[paperSingleIndex]?.optionD !== ' '
              "
              >D:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + singleChoice[paperSingleIndex]?.optionD"
            /></el-radio>

            <el-radio
              :label="6"
              data-key="e"
              v-if="
                !questionClass &&
                singleChoice[paperSingleIndex]?.optionE.length > 0 &&
                singleChoice[paperSingleIndex]?.optionE !== ' '
              "
              >E:
              <div>{{ singleChoice[paperSingleIndex]?.optionE }}</div></el-radio
            >
            <el-radio
              :label="6"
              data-key="e"
              v-if="
                questionClass &&
                singleChoice[paperSingleIndex]?.optionE.length > 0 &&
                singleChoice[paperSingleIndex]?.optionE !== ' '
              "
              >D:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + singleChoice[paperSingleIndex]?.optionE"
            /></el-radio>
          </el-radio-group>
          <imagePreview
            class="showimgView"
            v-if="singleChoice[paperSingleIndex].imgAddr"
            :src="url + singleChoice[paperSingleIndex]?.imgAddr"
          />
         </div>
        </aside>
        <aside
          class="testContent"
          v-if="title === '判断题' && judgeChoice.length > 0"
        >
          <div class="questionTitle">
            {{ judgeChoice[judgeChoiceIndex]?.questionNumber }}、{{
              judgeChoice[judgeChoiceIndex]?.questionName
            }}
            <span class="answer"> {{ checkedNum }}</span>
            <imagePreview
              class="showimgView"
              v-if="judgeChoice[judgeChoiceIndex].imgAddr"
              :src="url + judgeChoice[judgeChoiceIndex]?.imgAddr"
            />
          </div>
          <el-radio-group v-model="radio" @change="radioChange">
            <el-radio :label="2" v-if="!questionClass"
              >A:{{ judgeChoice[judgeChoiceIndex]?.optionA }}</el-radio
            >
            <el-radio :label="2" v-if="questionClass"
              >A:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + judgeChoice[judgeChoiceIndex]?.optionA"
            /></el-radio>
            <el-radio :label="3" v-if="!questionClass"
              >B:{{ judgeChoice[judgeChoiceIndex]?.optionB }}</el-radio
            >
            <el-radio :label="3" v-if="questionClass"
              >B:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + judgeChoice[judgeChoiceIndex]?.optionB"
            /></el-radio>
          </el-radio-group>
        </aside>
        <aside
          class="testContent"
          v-if="title === '多选题' && multipleChoice.length > 0"
        >
          <div class="questionTitle">
            {{ multipleChoice[multipleChoiceIndex]?.questionNumber }}、{{
              multipleChoice[multipleChoiceIndex]?.questionName
            }}
            <span class="answer"> {{ checkedNum }}</span>
            <imagePreview
              class="showimgView"
              v-if="multipleChoice[multipleChoiceIndex].imgAddr"
              :src="url + multipleChoice[multipleChoiceIndex]?.imgAddr"
            />
          </div>
          <el-checkbox-group
            v-model="checkList"
            @keydown="toggleCheckbox($event)"
            @change="radioChange"
          >
            <el-checkbox label="A" v-if="!questionClass"
              >A:
              <div>
                {{ multipleChoice[multipleChoiceIndex]?.optionA }}
              </div></el-checkbox
            >
            <el-checkbox label="A" v-if="questionClass"
              >A:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + multipleChoice[multipleChoiceIndex]?.optionA"
            /></el-checkbox>
            <el-checkbox label="B" v-if="!questionClass"
              >B:
              <div>
                {{ multipleChoice[multipleChoiceIndex]?.optionB }}
              </div></el-checkbox
            >
            <el-checkbox label="B" v-if="questionClass"
              >B:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + multipleChoice[multipleChoiceIndex]?.optionB"
            /></el-checkbox>
            <el-checkbox label="C" v-if="!questionClass"
              >C:
              <div>
                {{ multipleChoice[multipleChoiceIndex]?.optionC }}
              </div></el-checkbox
            >
            <el-checkbox label="C" v-if="questionClass"
              >C:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + multipleChoice[multipleChoiceIndex]?.optionC"
            /></el-checkbox>
            <el-checkbox
              label="D"
              v-if="
                !questionClass &&
                multipleChoice[multipleChoiceIndex]?.optionD &&
                multipleChoice[multipleChoiceIndex]?.optionD !== ' '
              "
              >D:
              <div>
                {{ multipleChoice[multipleChoiceIndex]?.optionD }}
              </div></el-checkbox
            >
            <el-checkbox
              label="D"
              v-if="
                questionClass &&
                multipleChoice[multipleChoiceIndex]?.optionD &&
                multipleChoice[multipleChoiceIndex]?.optionD !== ' '
              "
              >D:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + multipleChoice[multipleChoiceIndex]?.optionD"
            /></el-checkbox>
            <el-checkbox
              label="E"
              v-if="
                !questionClass &&
                multipleChoice[multipleChoiceIndex]?.optionE &&
                multipleChoice[multipleChoiceIndex]?.optionE !== ' '
              "
              >E:
              <div>
                {{ multipleChoice[multipleChoiceIndex]?.optionE }}
              </div></el-checkbox
            >
            <el-checkbox
              label="E"
              v-if="
                questionClass &&
                multipleChoice[multipleChoiceIndex]?.optionE &&
                multipleChoice[multipleChoiceIndex]?.optionE !== ' '
              "
              >E:
              <image-preview
                style="width: 110px; height: 70px"
                :src="url + multipleChoice[multipleChoiceIndex]?.optionE"
            /></el-checkbox>
          </el-checkbox-group>
        </aside>
        <footer class="operationBtn">
          <content>
            <div @click="previousHandle">
              <div class="leftIcon"></div>
              <span>上一题</span>
            </div>
            <div @click="signHandle">
              <div class="starIcon"></div>
              <span>标记</span>
            </div>
            <div @click="nextHandle">
              <div class="rightIcon"></div>
              <span>下一题</span>
            </div>
          </content>
        </footer>
      </article>
    </aside>
    <article class="bottomCollapse">
      <div class="bottomIcon">
        <div>
          <div class="gray"></div>
          &ensp; <span>未做</span>
        </div>
        <div>
          <div class="wathet"></div>
          &ensp; <span>已做</span>
        </div>
        <div>
          <div class="blue"></div>
          &ensp; <span>当前</span>
        </div>
        <div>
          <img src="../../assets/star.png" alt="" />&ensp; <span>待定</span>
        </div>
      </div>
      <div class="header">考生信息</div>
      <div class="titleContent">
        <imagePreview class="userImg" :src="url + ahExaminee.photograph" />
        <div class="userInfo">
          <div class="studentID">
            <span class="userTitle idTitle">考号:</span>
            <span class="idNumber">{{ ahExaminee.examNumber }}</span>
          </div>
          <div>
            <span class="userTitle">姓名:</span>
            <span>{{ ahExaminee.name }}</span>
          </div>
          <div>
            <span class="userTitle">性别:</span>
            <span>{{ sex() }}</span>
          </div>
          <div>
            <span class="userTitle">身份证号:</span>
            <span class="idNumber">{{ ahExaminee.idcard }}</span>
          </div>
        </div>
      </div>
    </article>

    <el-dialog
      title="警告"
      :visible.sync="centerDialogVisible"
      width="30%"
      style="font-size: 30px"
      center
    >
      <span>{{ alertData }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import $api from "../../utils/api";
import $Toast from "../../utils/toast.js";
import imagePreview from "../../components/ImagePreview/ImagePreview.vue";
export default {
  data() {
    return {
      //dirlog弹窗内容
      alertData: null,
      //dirlog弹窗
      centerDialogVisible: false,
      //请求地址
      // 192.168.110.22
      // 192.168.103.8
      //题目图片地址
      // url: "http://192.168.110.32:8900",//线下
      url: "http://103.14.133.68:8900",//线上
      //websocket地址
      // wcUrl: "ws://10.1.85.5:8900/websocket/ahtj/",
      wcUrl: "ws://103.14.133.68:8900/websocket/ahtj/",
      //websocket初始化
      ws: null,
      //考生身份信息
      idcard: localStorage.getItem("idcard") || "",
      activeNames: ["1", "2", "3"],
      radio: 1,
      checkList: [],
      //题目名称
      title: "单选题",
      //考生答案
      checkedNum: null,
      //考生所有信息
      userTextInfo: null,
      //考生个人信息
      ahExaminee: null,
      //考生试卷信息
      paper: null,
      //考试信息
      session: null,
      //试题数据
      paperQuestionListData: [],
      //单选
      singleChoice: [],
      //多选
      multipleChoice: [],
      //判断
      judgeChoice: [],
      //单选题试题索引
      paperSingleIndex: 0,
      //多选题试题索引
      multipleChoiceIndex: null,
      //判断题试题索引
      judgeChoiceIndex: null,
      //试题答案类型（文字还是图片）
      questionClass: null,
      //判断题选项
      // radio: "1",
      //考试倒计时
      day: "00",
      hour: "00",
      min: "00",
      second: "00",
      //试题标记
      questionSign: false,
      //试题状态
      questionStatus: null,
      //考试倒计时(时间戳)
      timerResult: null,
      //切屏次数
      allowScreenNum: 0,
      //交卷前最后一题id
      lastQuestionId: null,
      lastId: null,
      //考生答题答案
      answerDaata: [],
      //全屏状态
      isFullscreen: true,
      //考生id
      id: null,
      //考试最少交卷时间
      minTime: "",
    };
  },
  components: {
    imagePreview: imagePreview,
  },
  created() {
    //进入默认全屏
    // var isFullscreen = this.$route.query.isFullscreen;
    // if (isFullscreen) {
    //   this.requestFullScreen();
    // }
    //考生信息分类
    let userTextInfo = localStorage.getItem("userTextInfo");
    let resultOne = JSON.parse(userTextInfo);
    var resultTwo = this.$route.query.userTextInfo;
    this.userTextInfo = resultOne || resultTwo;
    this.ahExaminee = this.userTextInfo.ahExaminee;
    this.paper = this.userTextInfo.paper;
    this.paperQuestionListData = this.userTextInfo.questions;
    this.session = this.userTextInfo.session;
    this.id = this.userTextInfo.ahExaminee.id || "";
    console.log(this.userTextInfo.ahExaminee);

    //考试倒计时
    this.countDown();
    //试题分类
    this.questionsType();
    //再次进入页面展示第一题答案
    this.showOverAnswer(this.singleChoice[0].myAnswer);
  },
  mounted() {
    //websocket初始化
    this.init();
    document.addEventListener('keydown', this.handleKeydown);
    //监听切屏次数
    document.addEventListener("visibilitychange", this.handleVisiable);
    document.addEventListener(
      "wheel",
      function (event) {
        // 检查Ctrl键是否被按下
        if (event.ctrlKey) {
          // 阻止默认行为，即禁止缩放
          event.preventDefault();
        }
      },
      { passive: false }
    );
    // document.addEventListener("keydown", (event) => {

    // });
  },
  beforeDestroy() {
    // 组件销毁前，关闭WebSocket连接
    if (this.ws) {
      this.ws.close();
    }
  },
  destroyed() {
    document.removeEventListener("visibilitychange", this.handleVisiable);
  },
  computed: {},
  methods: {
    // handleKeydown(event) {
    //   if (event.key === 'Escape' || event.keyCode === 27) {
    //     event.preventDefault(); // 阻止默认行为
    //     console.log('ESC键被按下，但已被阻止');
    //   }
    // },
    sex() {
      // 获取倒数第二位数字
      const genderIndicator = this.ahExaminee.idcard.charAt(16);

      // 判断奇偶性
      if (parseInt(genderIndicator, 10) % 2 === 0) {
        return "女";
      } else {
        return "男";
      }
    },
    //键盘控制选项
    handleKeyDown(event) {
      const radios = document.querySelectorAll(".el-radio");
      let currentIndex = Array.from(radios).findIndex((radio) =>
        radio.classList.contains("is-active")
      );
      // 判断按下的是否是上下按键
      switch (event.key) {
        case "ArrowDown":
          if (currentIndex < radios.length - 1) {
            currentIndex++;
          } else {
            currentIndex = 0; // 循环到第一个选项
          }
          break;
        case "ArrowUp":
          if (currentIndex > 0) {
            currentIndex--;
          } else {
            currentIndex = radios.length - 1; // 循环到最后一个选项
          }
          break;
        default:
          return; // 忽略其他按键
      }
      // 将焦点移动到当前选中的单选框
      this.$nextTick(() => {
        radios[currentIndex].focus();
      });
      this.selectedValue = radios[currentIndex].value; // 更新绑定的值
    },
    toggleCheckbox(event) {
      const checkboxes = document.querySelectorAll(".el-checkbox__input");
      const spaceKeyCode = 32;
      const enterKeyCode = 13;

      // 确保是空格键或回车键
      if (event.keyCode === spaceKeyCode || event.keyCode === enterKeyCode) {
        event.preventDefault();
        const focusedCheckbox = document.activeElement;
        const isChecked = focusedCheckbox.checked;
        focusedCheckbox.checked = !isChecked; // 切换当前多选框的选中状态

        // 等待 DOM 更新后，更新绑定的数据
        this.$nextTick(() => {
          this.checkList = Array.from(checkboxes).reduce((acc, cb) => {
            if (cb.checked) acc.push(cb.value);
            return acc;
          }, []);
        });
      }
    },
    //上一题
    previousHandle() {
      if (this.checkedNum && this.checkedNum !== null) {
        this.savaQuestion();
      }
      if (this.title == "单选题") {
        if (this.paperSingleIndex > 0) {
          this.paperSingleIndex--;
          this.typeHandle(this.singleChoice, this.paperSingleIndex);
          this.lastQuestionId = this.singleChoice[this.paperSingleIndex].id;
          this.showOverAnswer(
            this.singleChoice[this.paperSingleIndex].myAnswer
          );
        } else {
          $Toast.messageWarning("已经是第一题!");
        }
      }

      if (this.title == "多选题") {
        if (this.multipleChoiceIndex > 0) {
          this.multipleChoiceIndex--;
          this.typeHandle(this.multipleChoice, this.multipleChoiceIndex);
          this.lastQuestionId =
            this.multipleChoice[this.multipleChoiceIndex].id;
          this.showOverAnswer(
            this.multipleChoice[this.multipleChoiceIndex].myAnswer
          );
        } else if (this.singleChoice.length > 0) {
          this.clickQuestionHandle(
            this.singleChoice.length - 1,
            "单选题",
            this.singleChoice
          );
          this.judgeChoiceIndex = null;
          this.multipleChoiceIndex = null;
          $Toast.messageWarning("开始单选题答题!");
          return;
        }
      }
      if (this.title == "判断题") {
        if (this.judgeChoiceIndex > 0) {
          this.judgeChoiceIndex--;
          this.typeHandle(this.judgeChoice, this.judgeChoiceIndex);
          this.lastQuestionId = this.judgeChoice[this.judgeChoiceIndex].id;
          this.showOverAnswer(this.judgeChoice[this.judgeChoiceIndex].myAnswer);
        } else if (this.multipleChoice.length > 0) {
          this.clickQuestionHandle(
            this.multipleChoice.length - 1,
            "多选题",
            this.multipleChoice
          );
          this.judgeChoiceIndex = null;
          this.paperSingleIndex = null;
          $Toast.messageWarning("开始多选题答题!");
          return;
        } else if (this.judgeChoice.length > 0) {
          this.clickQuestionHandle(
            this.singleChoice.length - 1,
            "单选题",
            this.singleChoice
          );
          this.judgeChoiceIndex = null;
          this.multipleChoiceIndex = null;
          $Toast.messageWarning("开始单选题答题!");
          return;
        }
      }
    },
    //下一题
    nextHandle() {
      if (this.checkedNum && this.checkedNum !== null) {
        this.savaQuestion();
      }

      if (this.title == "单选题") {
        if (this.paperSingleIndex < this.singleChoice.length - 1) {
          this.paperSingleIndex++;
          this.typeHandle(this.singleChoice, this.paperSingleIndex);
          this.lastQuestionId = this.singleChoice[this.paperSingleIndex].id;
          this.showOverAnswer(
            this.singleChoice[this.paperSingleIndex].myAnswer
          );
        } else if (this.multipleChoice.length > 0) {
          this.clickQuestionHandle(0, "多选题", this.multipleChoice);
          this.paperSingleIndex = null;
          this.judgeChoiceIndex = null;
          $Toast.messageWarning("开始多选题答题!");
          return;
        } else if (this.judgeChoice.length > 0) {
          this.clickQuestionHandle(0, "判断题", this.judgeChoice);
          this.paperSingleIndex = null;
          this.multipleChoiceIndex = null;
          $Toast.messageWarning("开始判断题答题!");
          return;
        }
      }
      if (this.title == "多选题") {
        if (this.multipleChoiceIndex < this.multipleChoice.length - 1) {
          this.multipleChoiceIndex++;
          // this.checkList=null
          this.typeHandle(this.multipleChoice, this.multipleChoiceIndex);
          this.lastQuestionId =
            this.multipleChoice[this.multipleChoiceIndex].id;
          this.showOverAnswer(
            this.multipleChoice[this.multipleChoiceIndex].myAnswer
          );
        } else if (this.judgeChoice.length > 0) {
          this.clickQuestionHandle(0, "判断题", this.judgeChoice);
          this.paperSingleIndex = null;
          this.multipleChoiceIndex = null;
          $Toast.messageWarning("开始判断题答题!");
          return;
        }
      }
      if (this.title == "判断题") {
        if (this.judgeChoiceIndex < this.judgeChoice.length - 1) {
          this.judgeChoiceIndex++;
          this.typeHandle(this.judgeChoice, this.judgeChoiceIndex);
          this.lastQuestionId = this.judgeChoice[this.judgeChoiceIndex].id;
          this.showOverAnswer(this.judgeChoice[this.judgeChoiceIndex].myAnswer);
        } else {
          $Toast.messageWarning("已经是最后一题!");
        }
      }
    },
    //保存答案
    savaQuestion() {
      if (
        this.paperSingleIndex >= 0 &&
        this.multipleChoiceIndex >= 0 &&
        this.judgeChoiceIndex >= 0
      ) {
        let questionId = null;
        let myAnswer = this.checkedNum;
        let questionStatus = this.questionStatus;
        let status = null;
        if (this.title == "单选题") {
          questionId = this.singleChoice[this.paperSingleIndex].id;
          status = this.singleChoice[this.paperSingleIndex].status;
        } else if (this.title == "多选题") {
          questionId = this.multipleChoice[this.multipleChoiceIndex].id;
          status = this.multipleChoice[this.multipleChoiceIndex].status;
          if (myAnswer !== null) {
            myAnswer = myAnswer.split("").sort().join("");
          }
        } else if (this.title == "判断题") {
          questionId = this.judgeChoice[this.judgeChoiceIndex].id;
          status = this.judgeChoice[this.judgeChoiceIndex].status;
        }
        if (status !== "2") {
          this.checkedNum !== null
            ? (questionStatus = "1")
            : (questionStatus = "0");
        } else {
          questionStatus = "2";
        }
        new Promise((resolve, reject) => {
          $api
            .savaQuestion({
              id: questionId,
              myAnswer: myAnswer,
              status: questionStatus,
            })
            .then((res) => {
              if (res.status == 200) {
                let questions =
                  JSON.parse(localStorage.getItem("questions"))?.questions ||
                  this.paperQuestionListData;
                let currentIndex;
                questions.findIndex((item, index) => {
                  if (item.id == questionId) {
                    currentIndex = index;
                  }
                });
                questions[currentIndex].myAnswer = myAnswer;
                localStorage.setItem("questions", JSON.stringify(questions));
                this.paperQuestionListData = questions;
                this.questionsType();
                // $api
                //   .stuLogin({
                //     idcard: this.idcard,
                //   })
                //   .then((res) => {
                //     this.paperQuestionListData = res.data?.data?.questions;
                //     this.questionsType();
                //   });
              } else {
                reject(res.statusText);
              }
            });
        });
      }
    },
    //标记
    signHandle() {
      let singleItem = this.singleChoice[this.paperSingleIndex];
      let multipleItem = this.multipleChoice[this.multipleChoiceIndex];
      let judgeItem = this.judgeChoice[this.judgeChoiceIndex];
      let title = this.title;
      if (title == "单选题") {
        if (singleItem.status !== "2") {
          this.$set((singleItem.status = "2"));
        } else {
          this.checkedNum !== null
            ? this.$set((singleItem.status = "1"))
            : this.$set((singleItem.status = "0"));
        }
      } else if (title == "判断题") {
        if (judgeItem.status !== "2") {
          this.$set((judgeItem.status = "2"));
        } else {
          this.checkedNum !== null
            ? this.$set((judgeItem.status = "1"))
            : this.$set((judgeItem.status = "0"));
        }
      } else if (title == "多选题") {
        if (multipleItem.status !== "2") {
          this.$set((multipleItem.status = "2"));
        } else {
          this.checkedNum !== null
            ? this.$set((multipleItem.status = "1"))
            : this.$set((multipleItem.status = "0"));
        }
      }

      $api
        .stuLogin({
          idcard: this.idcard,
        })
        .then((res) => {
          this.paperQuestionListData = res.data?.data?.questions;
          this.questionsType();
        });
    },
    //左边题目顺序折叠
    handleChange(val) {
      // if (val == 3) {
      //   // this.title = "判断题";
      // } else if (val == 2) {
      //   // this.title = "多选题";
      // } else if (val == 1) {
      //   // this.title = "单选题";
      // }
    },
    //radio选项
    radioChange(e) {
      if (this.title == "多选题") {
        let res = this.checkList;
        switch (res.length) {
          case 0:
            this.checkedNum = null;
            break;
          case 1:
            this.checkedNum = res[0];
            break;
          case 2:
            this.checkedNum = res[0] + res[1];
            break;
          case 3:
            this.checkedNum = res[0] + res[1] + res[2];
            break;
          case 4:
            this.checkedNum = res[0] + res[1] + res[2] + res[3];
            break;
          case 5:
            this.checkedNum = res[0] + res[1] + res[2] + res[3] + res[4];
            break;
        }
        if (this.checkedNum !== null && this.checkedNum) {
          this.checkedNum = this.checkedNum.split("").sort().join("");
        }
      } else {
        switch (e) {
          case 2:
            this.checkedNum = "A";
            break;
          case 3:
            this.checkedNum = "B";
            break;
          case 4:
            this.checkedNum = "C";
            break;
          case 5:
            this.checkedNum = "D";
            break;
          case 6:
            this.checkedNum = "E";
            break;
        }
      }
    },
    /////已答问题答案展示判断
    showOverAnswer(data) {
      if (this.title == "多选题") {
        if (data == null) {
          this.checkList = [];
        } else {
          this.checkList = data.split("");
        }
        this.checkedNum = data;
      } else {
        switch (data) {
          case "A":
            this.radio = 2;
            this.checkedNum = "A";
            break;
          case "B":
            this.radio = 3;
            this.checkedNum = "B";
            break;
          case "C":
            this.radio = 4;
            this.checkedNum = "C";
            break;
          case "D":
            this.radio = 5;
            this.checkedNum = "D";
            break;
          case "E":
            this.radio = 6;
            this.checkedNum = "E";
            break;
          default:
            this.radio = 1;
            this.checkedNum = null;
        }
      }
    },
    //试题类型分类
    questionsType() {
      let singleChoice = [];
      let multipleChoice = [];
      let judgeChoice = [];
      this.paperQuestionListData.map((item, index) => {
        //B单选题  //C判断题 //D多选题
        if (item.questionType == "B") {
          singleChoice.push(item);
          this.singleChoice = singleChoice;
          this.lastQuestionId = this.singleChoice[0].id;
        }
        if (item.questionType == "C") {
          judgeChoice.push(item);
          this.judgeChoice = judgeChoice;
          this.lastQuestionId = this.judgeChoice[0].id;
        }
        if (item.questionType == "D") {
          multipleChoice.push(item);
          this.multipleChoice = multipleChoice;
          this.lastQuestionId = this.multipleChoice[0].id;
        }
      });
    },
    //点击左侧题目列表
    clickQuestionHandle(index, title, questionData) {
      // console.log(this.checkedNum);
      if (this.checkedNum && this.checkedNum !== null) {
        this.savaQuestion();
      }
      this.clickHandle(index, title);
      this.typeHandle(questionData, index);
    },
    //点击试题操作
    clickHandle(index, title) {
      this.title = title;
      this.radio = null;
      this.checkedNum = null;
      if (title == "单选题") {
        this.paperSingleIndex = index;
        this.judgeChoiceIndex = null;
        this.multipleChoiceIndex = null;
        this.lastQuestionId = this.singleChoice[index].id;
        this.showOverAnswer(this.singleChoice[index].myAnswer);
      }
      if (title == "判断题") {
        this.judgeChoiceIndex = index;
        this.paperSingleIndex = null;
        this.multipleChoiceIndex = null;
        this.lastQuestionId = this.judgeChoice[index].id;
        this.showOverAnswer(this.judgeChoice[index].myAnswer);
      }
      if (title == "多选题") {
        this.multipleChoiceIndex = index;
        this.paperSingleIndex = null;
        this.judgeChoiceIndex = null;
        this.lastQuestionId = this.multipleChoice[index].id;
        this.showOverAnswer(this.multipleChoice[index].myAnswer);
      }
    },
    //判断展示题目是图片还是文字
    typeHandle(type, index) {
      let result1 = type[index]?.optionA.indexOf("jpg");
      let result2 = type[index]?.optionA.indexOf("png");
      let result3 = type[index]?.optionA.indexOf("jpeg");
      if (result1 == -1 && result2 == -1 && result3 == -1) {
        this.questionClass = false;
      } else {
        this.questionClass = true;
      }
    },
    //计算考试倒计时
    countDown() {
      var timer = setInterval(() => {
        let futureDateTime = new Date().getTime();
        let endTime = new Date(this.session.endTime);
        let nowTimestamp = endTime.getTime();
        let timeStamp = nowTimestamp - futureDateTime;
        // 设置定时器 一秒更新一次数据
        if (timeStamp <= 0) {
          // 如果到0了以后清除定时器
          this.submitPaper(1);
          clearInterval(timer);
          return;
        }
        // 计算剩余的天数、小时、分钟和秒
        this.day = Math.floor(timeStamp / (1000 * 60 * 60 * 24));
        this.hour = Math.floor(
          (timeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)
        );
        this.min = Math.floor((timeStamp % (1000 * 60 * 60)) / (1000 * 60));
        this.second = Math.floor((timeStamp % (1000 * 60)) / 1000);
      }, 1000);
    },
    //交卷
    // 考生id，交卷类型（0主动交卷，1自动交卷，2强制交卷）
    async submitPaper(type) {
      if (
        this.paperSingleIndex >= 0 &&
        this.multipleChoiceIndex >= 0 &&
        this.judgeChoiceIndex >= 0
      ) {
        let questionId = null;
        let myAnswer = this.checkedNum;
        let questionStatus = this.questionStatus;
        let status = null;
        if (this.title == "单选题") {
          questionId = this.singleChoice[this.paperSingleIndex].id;
          status = this.singleChoice[this.paperSingleIndex].status;
        } else if (this.title == "多选题") {
          questionId = this.multipleChoice[this.multipleChoiceIndex].id;
          status = this.multipleChoice[this.multipleChoiceIndex].status;
        } else if (this.title == "判断题") {
          questionId = this.judgeChoice[this.judgeChoiceIndex].id;
          status = this.judgeChoice[this.judgeChoiceIndex].status;
        }
        if (status !== "2") {
          this.checkedNum !== null
            ? (questionStatus = "1")
            : (questionStatus = "0");
        } else {
          questionStatus = "2";
        }
        $api
          .savaQuestion({
            id: questionId,
            myAnswer: myAnswer,
            status: questionStatus,
          })
          .then((res) => {
            if (res.status == 200) {
              $api
                .stuLogin({
                  idcard: this.idcard,
                })
                .then((res) => {
                  var num = 0;
                  if (res.data?.data?.questions) {
                    this.paperQuestionListData = res.data?.data?.questions;
                    let paperQuestionListData = this.paperQuestionListData;
                    paperQuestionListData.forEach((item, index) => {
                      if (item.myAnswer == null) {
                        num += 1;
                      }
                    });
                  }
                  if (type == 2) {
                    // 强制交卷
                    this.testTimeOver(2);
                  } else if (type == 0) {
                    console.log(typeof num, "num");
                    if (num !== undefined && typeof num === "number") {
                      this.$confirm(
                        num == 0
                          ? "已完成全部题目，是否交卷？"
                          : "还有" + num + "道题目未完成,是否确认交卷?",
                        "提示",
                        {
                          confirmButtonText: "确定",
                          cancelButtonText: "取消",
                          type: "warning",
                          center: true,
                        }
                      )
                        .then(() => {
                          // 主动交卷提前三十分钟不能交卷
                          //获取开考时间
                          let minTime = this.paper.minTime;
                          let userTextInfo =
                            localStorage.getItem("userTextInfo");
                          let startTime =
                            JSON.parse(userTextInfo).session.startTime;
                          var pastTime = new Date(startTime);
                          var now = new Date();
                          var diffInMilliseconds = now - pastTime;
                          var diffInMinutes = diffInMilliseconds / 60000; // 1分钟 = 60000毫秒
                          // 判断差值是否小于minTime分钟
                          if (diffInMinutes < minTime) {
                            // console.log("时间差小于minTime分钟");
                            this.$alert(
                              "不能提前" + minTime + "分钟交卷,请稍后进行操作",
                              "提示",
                              {
                                confirmButtonText: "确定",
                              }
                            );
                          } else {
                            // console.log('可以交卷');
                            this.testTimeOver(0);
                          }
                          // console.log(pastTime);
                        })
                        .catch(() => {
                          this.$message({
                            type: "info",
                            message: "已取消!",
                          });
                        });
                    }
                  } else if (type == 1) {
                    this.$alert("考试结束，三秒后自动交卷!", "提示", {
                      confirmButtonText: "确定",
                    });
                    setTimeout(() => {
                      //自动交卷
                      this.testTimeOver(1);
                    }, 3000);
                  }
                });
            }
          });
      }
    },
    testTimeOver(type) {
      let id = this.ahExaminee.id;
      $api
        .submitPaper({
          examineeId: id,
          handPaperType: type,
        })
        .then((res) => {
          if (res.status == 200 && res.data.code == 200) {
            this.$router.push({
              name: "grade",
              query: {
                grade: res.data.data,
              },
            });
            this.$message({
              type: "success",
              message: "交卷成功!",
            });
          }
        });
    },
    //切出页面超过一定次数强制交卷
    handleVisiable(e) {
      console.log(e);
      let maxAllowScreenNum = this.paper.allowScreenNum;
      switch (e.target.visibilityState) {
        case "prerender":
          break;
        case "hidden":
          this.allowScreenNum += 1;
          if (this.allowScreenNum <= maxAllowScreenNum - 1) {
            this.$confirm(
              "监测到您已切出考试界面" +
                this.allowScreenNum +
                "次！请遵守考试规则！",
              "提示",
              {
                confirmButtonText: "确定",
                showCancelButton: false,
                showClose: true,
                center: true,
              }
            );
          }
          if (this.allowScreenNum == maxAllowScreenNum) {
            this.alertData = "您已违规操作，即将强制交卷！";
            this.centerDialogVisible = true;
            setTimeout(() => {
              this.submitPaper(2);
            }, 3000);
          }
          break;
        case "visible":
          break;
      }
    },
    //init函数可在页面加载的时候就进行初始化或者根据自己的业务需求在需要打开通讯的时候在进行初始化
    init() {
      if ("WebSocket" in window) {
        // 打开一个 web socket
        var ws = new WebSocket(this.wcUrl + this.id);
        ws.onopen = function () {};
        ws.onmessage = function (evt) {
          func1(evt);
        };
        let func2 = function func3(evt) {
          if (evt.data !== "连接成功") {
            this.alertData = evt.data;
            this.centerDialogVisible = true;
          }
        };
        let func1 = func2.bind(this);
        ws.onerror = (error) => {};
        ws.onclose = function () {};
      } else {
        alert("您的浏览器不支持 WebSocket!");
      }
    },
    //强制交卷
    dialogVisible() {
      this.centerDialogVisible = false;
      if (this.alertData == "您已被强制结束考试！") {
        // //交卷
        this.testTimeOver(2);
      }
    },
    //全屏
    // requestFullScreen() {
    //   let de = document.documentElement;
    //   if (de.requestFullscreen) {
    //     de.requestFullscreen();
    //   } else if (de.mozRequestFullScreen) {
    //     de.mozRequestFullScreen();
    //   } else if (de.webkitRequestFullScreen) {
    //     de.webkitRequestFullScreen();
    //   }
    // },
  },
};
import "@/views/examination/examination.scss";
</script>